<template>
  <div class="container_warp">
    <!-- 画布 -->
    <div id="containerChart"></div>
    <!-- 画布属性配置 -->
    <RightDrawer class="right_drawer" :graph="graph" :drawerType="type" :grid="grid" :selectCell="selectCell" @deleteNode="deleteNode"></RightDrawer>
    <!-- 操作栏 -->
    <div class="operating">
        <div class="btn-group">
          <div class="btn" title="圆形节点" @mousedown="startDrag('Circle',$event)">
            <i class="iconfont icon-yuanxingweixuanzhong"></i>
          </div>
          <div class="btn" title="矩形节点" @mousedown="startDrag('Rect',$event)">
            <i class="iconfont icon-juxing"></i>
          </div>
          <div class="btn" title="条件节点" @mousedown="startDrag('polygon',$event)">
            <i class="iconfont icon-lingxing"></i>
          </div>
          <div class="btn" title="变电站" @mousedown="startDrag('bdz',$event)">
            <i class="iconfont icon-biandianzhan"></i>
          </div>
          <div class="btn-group_tips" v-if="showTips">
            拖拽生成<br/>图形
          </div>
        </div>
        <div class="btn-group">
          <el-tooltip content="直线箭头" placement="bottom">
              <div :class=" ['btn',currentArrow === 1?'currentArrow':'']" @click="changeEdgeType('normal')">
                <i class="iconfont icon-line-arrow"></i>
              </div>
          </el-tooltip>
          <el-tooltip content="曲线箭头" placement="bottom">
              <div :class=" ['btn',currentArrow === 2?'currentArrow':'']" @click="changeEdgeType('smooth')">
                <i class="iconfont icon-quxianjiantou"></i>
              </div>
          </el-tooltip>
          <el-tooltip content="直角箭头" placement="bottom">
              <div :class=" ['btn',currentArrow === 3?'currentArrow':'']" @click="changeEdgeType()">
                <i class="iconfont icon-subdirectory_arrow_right"></i>
              </div>
          </el-tooltip>
        </div>
        <div class="btn-group">
          <el-tooltip content="删除" placement="bottom">
              <div class="btn" @click="deleteNode()" style="margin-top: 5px;">
                <i class="iconfont icon-shanchu"></i>
              </div>
          </el-tooltip>
          <el-tooltip content="保存PNG" placement="bottom">
              <div class="btn" @click="saveToPNG()" title="保存">
                <i class="iconfont icon-baocun"></i>
              </div>
          </el-tooltip>
          <el-tooltip content="保存JSON数据" placement="bottom">
              <div class="btn" @click="saveJSON()" title="保存">
                <i class="iconfont icon-baocun"></i>
              </div>
          </el-tooltip>
        </div>
      </div>
  </div>
</template>

<script>
// import '@antv/x6-vue-shape';
import { Graph,Shape,Addon,FunctionExt,DataUri} from '@antv/x6';
import RightDrawer from '../components/RightDrawer';
import { startDragToGraph } from './graph/methods.js';
export default {
    name: 'index',
    components: {RightDrawer},
    data() {
        return {
            data: {},
            // RightDrawer组件属性配置
            graph:'',
            type:'grid', // 配置面板对应左侧节点类型
            selectCell: '',
            connectEdgeType:{  //连线方式
                connector: 'normal',
                router: {
                    name: ''
                }
            },
            grid:{ // 网格设置
                size: 20,      // 网格大小 10px
                visible: true, // 渲染网格背景
                type: 'mesh',
                args: {
                    color: '#D0D0D0',
                    thickness: 1,     // 网格线宽度/网格点大小
                    factor: 10, 
                },
            },
            showTips: false, // 拖拽提示
            currentArrow: 1,//默认激活索引
        }
    },
    mounted() {
        this.initX6();
        // 页面加载1秒后显示提示
        setTimeout(()=>{
          this.showTips = true
        },1000)
        // 5秒后提示消失
        setTimeout(()=>{
          this.showTips = false
        },5000)
    },
    methods: {
        // 初始化X6画布
        initX6(){
            var _that = this;
            this.graph = new Graph({
                container: document.getElementById('containerChart'),
                width: 1536,
                height: '100%',
                grid: _that.grid,
                resizing: { //调整节点宽高
                  enabled: true,
                  orthogonal:false,
                }, 
                selecting: true, //可选
                snapline:  true,
                interacting: {
                  edgeLabelMovable: true
                },
                connecting: { // 节点连接
                  anchor: 'center',
                  connectionPoint: 'anchor',
                  allowBlank: true,
                  snap: true,
                  createEdge () {
                    return new Shape.Edge({
                      attrs: {
                        line: {
                          stroke: '#1890ff',
                          strokeWidth: 1,
                          targetMarker: 0, //取消箭头
                          // 保留箭头
                          // targetMarker: {
                          //   name: 'classic',
                          //   size: 8
                          // },
                          strokeDasharray: 0, //虚线
                          style: {
                            animation: 'ant-line 30s infinite linear',
                          },
                        },
                      },
                      label: {
                        text:''
                      },
                      connector: _that.connectEdgeType.connector,
                      router: {
                        name: _that.connectEdgeType.router.name || ''
                      },
                      zIndex: 0
                    })
                  },
                },
                highlighting: {
                  magnetAvailable: {
                    name: 'stroke',
                    args: {
                      padding: 4,
                      attrs: {
                        strokeWidth: 4,
                        stroke: '#6a6c8a'
                      }
                    }
                  }
                },
            });
            // insertCss(`
            //   @keyframes ant-line {
            //     to {
            //         stroke-dashoffset: -1000
            //     }
            //   }
            // `)
            this.graph.fromJSON(this.data)
            this.graph.history.redo()
            this.graph.history.undo()
            // 鼠标移入节点
            this.graph.on('node:mouseenter',FunctionExt.debounce(() => {
                const container =  document.getElementById('containerChart')
                const ports = container.querySelectorAll(
                  '.x6-port-body'
                )
                this.showPorts(ports, true)
              }),
              500
            )
            // 鼠标移出节点
            this.graph.on('node:mouseleave', () => {
              const container =  document.getElementById('containerChart')
              const ports = container.querySelectorAll(
                '.x6-port-body'
              )
              this.showPorts(ports, false)
            })
            // 单击空白处
            this.graph.on('blank:click', () => {
              this.type = 'grid'
            })
            // 单击节点/边
            this.graph.on('cell:click', ({ cell }) => {
              this.type = cell.isNode() ? 'node' : 'edge';
            })
            // 选中的节点/边发生改变(增删)时触发
            this.graph.on('selection:changed', (args) => {
              args.added.forEach(cell => {
                this.selectCell = cell
                if(cell.isEdge()){
                 cell.isEdge() && cell.attr('line/strokeDasharray', 5) //虚线蚂蚁线
                 cell.addTools([
                    {
                      name: 'vertices',
                      args: {
                        padding: 4,
                        attrs: {
                          strokeWidth: 0.1,
                          stroke: '#2d8cf0',
                          fill: '#ffffff',
                        }
                      },
                    },
                  ])
                }
              })
              args.removed.forEach(cell => {
                cell.isEdge() && cell.attr('line/strokeDasharray', 0)  //正常线
                cell.removeTools()
              })
            })
        },
        // 删除节点
        deleteNode(){
          const cell = this.graph.getSelectedCells()
          this.graph.removeCells(cell)
          this.type = 'grid'
        },
        showPorts (ports, show) {
          for (let i = 0, len = ports.length; i < len; i = i + 1) {
            ports[i].style.visibility = show ? 'visible' : 'hidden'
          }
        },
        // 拖拽生成节点
        startDrag(type,e){
          startDragToGraph(this.graph,type,e)
        },
        // 改变边形状
        changeEdgeType(e){
          if(e === 'normal'){
            this.connectEdgeType = {
              connector: 'normal',
              router: {name: ''}
            }
            this.currentArrow = 1
          }else if (e === 'smooth'){
            this.connectEdgeType = {
              connector: 'smooth',
              router: {name: ''}
            }
            this.currentArrow = 2
          }else{
            this.connectEdgeType = {
              connector: 'normal',
              router: {name: 'manhattan'}
            }
            this.currentArrow = 3
          }
        },
        // 保存png
        saveToPNG(){
          this.$nextTick(()=>{
            this.graph.toPNG((dataUri) => {
            // 下载
              DataUri.downloadDataUri(dataUri, '拓扑图.png')
            },{
              backgroundColor: 'white',
              padding: {
                top: 50,
                right: 50,
                bottom: 50,
                left: 50
              },
              quality: 1,
              copyStyles:false
            })
          })
        },
        // 保存json数据
        saveJSON() {
          console.log(this.graph.toJSON());
        }
    },
}
</script>

<style scoped lang="less">
.container_warp{
    position: relative;
    width: 100%;
    height: 100vh;
    display: flex;
        .operating {
        position: absolute;
        top: 0;
        z-index: 99;
        background-color: #ffffff;
        padding: 20px 10px;
        box-shadow: 1px 1px 4px 0 #0a0a0a2e;
    }
}
.btn-group {
    border-right: 1px solid #efefef;
    display: inline-block;
    padding-left: 10px;
    padding-right: 14px;
    position: relative;
    .btn-group_tips {
        text-align: center;
        top: 63px;
        left: 1px;
        position: absolute;
        color: #fff;
        display: flex;
        align-items: center;
        justify-content: center;
        width: 120px;
        height: 60px;
        background: #515a6e;
        border-radius:6px;
        animation: tips 4s;
        transition: all 1s;
        &:after {
            content: "";
            width: 0;
            height: 0;
            position: absolute;
            top: -5px;
            left: 46%;
            border-width: 0 5px 5px;
            border-style: solid;
            border-color: transparent transparent #515a6e;
        }
    }
    &:last-of-type {
        border-right: 0;
    }
    .btn {
        display: inline-block;
        margin: 2px;
        width: 30px;
        height: 30px;
        line-height: 30px;
        text-align: center;
        cursor: pointer;
        transition: all .4s;
        border-radius: 6px;
        border: 1px solid rgba(233, 233, 233, 0);
        i {
            font-size: 20px;
        }
    }
    .currentArrow {
        background: #2d8cf0;
        color: #fff;
    }
}
@keyframes tips {
    0% {opacity: 0;transform:scale(0);}
    10% {opacity: 1;transform:scale(1);}
    90% {opacity: 1;transform:scale(1);}
    100% {opacity: 0;transform:scale(0);}
}
.rotate-square{
    display: inline-block;
    transform: rotate(45deg);
}
.my-snapline {
    color: #000;
}
.right_drawer {
    height: 100%;
    width: 300px;
    border-left: 1px solid #eee;
    background: #fff;
}
</style>